<template>

  <div class="new-page version-management-eng-box">
    <draggable
      class="h-100 d-flex flex-column"
      :group="{ name: 'people'}"
      filter=".undraggable"
      @add="removeItem"
    >

      <div class="pp-t-96 undraggable p16-a">
        <div class="p-vm-btn-box undraggable">
          <a-button ghost type="primary" @click="saveDraft">
            保存草稿
          </a-button>
          <a-button type="primary" class="ml-8" :disabled="flag===1" :loading="updateRepReportTemplateLoading" @click="update">
            保存修改
          </a-button>
          <a-button type="primary" class="ml-8" :loading="addRepReportTemplateLoading" @click="addVisible=true">
            发布新版本
          </a-button>
        </div>
        <div class="text-color-21252e">
          模版管理
        </div>
        <a-row>
          <a-col :span="20">
            <a-row :gutter="8">
              <a-col :span="8">
                <span class="text-color-505363 fs-12">模板名称：</span>
                <span class="text-color-505363 fs-12">{{ rowHis.reportName }}</span>
              </a-col>
              <a-col :span="8">
                <span class="text-color-505363 fs-12">模板状态：</span>
                <span class="text-color-505363 fs-12">{{ rowHis.enable===1?"启用":'禁用' }}</span>
              </a-col>
              <a-col :span="8">
                <span class="text-color-505363 fs-12">所属一级分类：</span>
                <span class="text-color-505363 fs-12">{{ rowHis.smi||'--' }}</span>
              </a-col>
              <a-col :span="8">
                <span class="text-color-505363 fs-12  jwhxz-lable">机号限制：</span>
                <span class="text-color-505363 fs-12 jwhxz-box">{{ tailnumbers||'--' }}</span>
              </a-col>

              <a-col :span="8">
                <span class="text-color-505363 fs-12 jwhxz-lable">描述：</span>
                <span class="text-color-505363 fs-12 jwhxz-box">{{ rowHis.description||'--' }}</span>
              </a-col>
              <a-col :span="8">
                <span class="text-color-505363 fs-12">所属二级分类：</span>
                <span class="text-color-505363 fs-12">{{ rowHis.imi||'--' }}</span>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </div>
      <div id="vm-pp-t-96" class="pp-rb-box version-management-eng  undraggable">
        <a-row class="flex-1 of-h coding-desgin-main-box">
          <!-- 标签 -->
          <a-col :span="4" class=" vm-tabs-main decoding-box-item decoding-box-item-3">

            <a-tabs :active-key="flag" :animated="false" class="d-flex flex-column" @change="changeFlag">
              <a-tab-pane :key="1" tab="草稿">
                <div
                  v-for="(item,index) in draftData"
                  :key="item.id+index"
                  :class="['his-item-box text-over',index===draftAc?'his-item-box-ac':'']"
                  class="his-item-box fs-12"
                  @click="draftClick(index)"
                >
                  {{ item.version }}

                  <a-dropdown placement="bottomRight">
                    <a-menu slot="overlay">
                      <a-menu-item>
                        <a @click="delItemHandler(item)">删除</a>
                      </a-menu-item>

                    </a-menu>
                    <a-icon :component="require('@/assets/icon/More_vertical.svg')" class="export-more" />
                  </a-dropdown>
                </div>
              </a-tab-pane>
              <a-tab-pane :key="2" tab="历史版本">
                <div
                  v-for="(item,index) in versionList"
                  :key="item+index"
                  :class="['his-item-box text-over',index===hisNameAc?'his-item-box-ac':'']"
                  class="his-item-box fs-12"
                  @click="hisClick(index)"
                >
                  {{ item.version }}
                  <!-- <a-popconfirm
                    title="确认删除此项?"
                    ok-type="danger"
                    ok-text="确认"
                    placement="bottom"
                    cancel-text="取消"
                    @confirm="delItemHandler(item)"
                  >
                    <a-icon :component="require('@/assets/icon/close.svg')" />
                  </a-popconfirm> -->

                  <a-dropdown placement="bottomRight">
                    <a-menu slot="overlay">
                      <a-menu-item>
                        <a @click="delItemHandler(item)">删除</a>
                      </a-menu-item>

                    </a-menu>
                    <a-icon :component="require('@/assets/icon/More_vertical.svg')" class="export-more" />
                  </a-dropdown>
                </div>
              </a-tab-pane>
            </a-tabs>
            <a-tabs default-active-key="1" :animated="false" class="d-flex flex-column vm-label-tabs">
              <a-tab-pane key="1" tab="默认参数标签">
                <VueTree :tree-data="showNormalLabel" :clone-dog="cloneDog" name-key="alias" children-key="children" />
              </a-tab-pane>
              <a-tab-pane key="2" tab="特殊参数标签">
                <VueTree :tree-data="showSystemLabel" :clone-dog="cloneDog" name-key="alias" children-key="children" />
                <!-- <a-input-search style="margin-bottom: 8px" placeholder="查询特殊参数标签" @click="focusSearch" @change="onSChange" /> -->
                <!-- <draggable
                  class="d-flex flex-column"
                  :list="showSystemLabel"
                  :group="{ name: 'people', pull: 'clone', put: false }"
                  :clone="cloneDog"
                >
                  <div
                    v-for="item in showSystemLabel"
                    :key="item.id"
                    class="draggable"
                  >
                    {{ item.labelName }}
                  </div>
                </draggable> -->
              </a-tab-pane>
            </a-tabs>
          </a-col>

          <!-- 设计 -->
          <div class="coding-design-box">
            <div>
              <a-tabs v-model="showDcodeDesign" @change="changeShowDcodeDesign">
                <a-tab-pane :key="1">
                  <div slot="tab">
                    <span>解码设计</span>
                    <!-- <a-tooltip placement="topLeft">
                      <template slot="title">
                        <span>勾选展示格式化占位符</span>
                      </template>
                      <a-checkbox :checked="displayFormat1" style="margin-left:4px" @click="clickTab" @change="displayFormat1=!displayFormat1" />
                    </a-tooltip> -->

                  </div>
                </a-tab-pane>
                <a-tab-pane :key="2">
                  <div slot="tab">
                    <span>显示设计</span>
                    <a-tooltip placement="topLeft">
                      <template slot="title">
                        <span>勾选展示模板源码</span>
                      </template>
                      <a-checkbox :checked="displayFormat2" style="margin-left:4px" @click="clickTab" @change="displayFormat2=!displayFormat2" />
                    </a-tooltip>

                  </div>
                </a-tab-pane>
              </a-tabs>
            </div>
            <a-spin :spinning="repReportVersionLoading">
              <div v-if="showDcodeDesign===2">
                <div :key="cKey" class="eng-html-box">
                  <engHtml v-if="displayFormat2===false" :key="cKey" :ele="tmpHtml" />
                </div>
                <!-- 用来渲染style -->
                <div v-show="false" v-html="headCode" />
                <!-- 用来 执行script标签内的document.write 渲染完整html-->
                <iframe id="rep-iframe-eng" class="iframe-eng" frameborder="0" />
              </div>
              <RecycleScroller
                v-else
                :key="cKey"
                :items="maxRow"
                :item-size="50"
              >

                <template slot-scope="{ item }">

                  <span
                    v-html="blockFormat(decodingDesign[item+1][0].alias)"
                  />
                  <draggable
                    class="h-100 d-flex-i-f ai-end vm-td-div "
                    :list="decodingDesign[item+1]||[]"
                    :group="{ name: 'people' }"
                    @change="(e)=>log(e,item+1)"
                  >

                    <template v-for="itemData in (decodingDesign[item+1]||[])">
                      <div
                        v-show="itemData.alias.indexOf('Serial_Number')===-1"
                        :key="itemData.rptDefSeq+itemData.alias"
                        :class="['list-group-item','vm-label-span-box',colonData.includes(itemData.alias)?'colon-data':'']"
                        :title="itemData.alias"
                      >

                        <editDiv v-model="itemData.alias" />

                      </div>

                    </template>

                  </draggable>

                </template>

              </RecycleScroller>
              <!--
                <div>
                  <span v-for="item in itemData" :key="item.col">
                    {{ item.alias }} ;
                  </span>
                </div> -->
              <!-- <a-col :span="24" class="h-100 decoding-box-item code-tmp-1 pl-10 pr-10">

                <table id="myTable" border="1">
                  <thead>
                    <tr>
                      <th class="vm-th" width="13" />
                      <th
                        v-for="(item,index) in colMax"
                        :key="item"
                        :class="[index===0||(index+1)%5===0?'vm-th-im':'']"
                        class="vm-th"
                        width="13"
                      >{{ item }}</th>
                    </tr>
                  </thead>

                  <tbody>
                    <tr v-for="item in maxRow" :key="item" class="vm-tr">
                      <td class="vm-td">{{ item+1 }}</td>

                    </tr>
                  </tbody>
                </table>
                <RecycleScroller
                  :items="maxRow"
                  :item-size="60"
                >

                  <template slot-scope="{ item }">

                    <draggable
                      class="h-100 d-flex-i-f ai-end vm-td-div"
                      :list="objData[item+1]||[]"
                      :group="{ name: 'people' }"
                      @change="(e)=>log(e,item+1)"
                    >
                      <template v-for="(item2,index) in (objData[item+1]?objData[item+1]:[])">
                        <div
                          :key="item2.id+''+index"
                          :class="['list-group-item',item2.groupName==='system'?'vm-label-span-box':'']"
                          :title="item2.value?item2.value:!displayFormat[showDcodeDesign]?item2.labelName:item2.displayFormat"
                          :style="{'width':`${13*(item2.width||1)-4}px`}"
                        >
                          <template v-if="item2.value">
                            <a-input v-if="item2.groupName!=='system'" v-model="item2.value" :title="item2.value" />
                            <span v-else class="vm-label-span" :title="item2.value">{{ item2.value }}</span>
                          </template>
                          <template v-if="!item2.value&&!displayFormat[showDcodeDesign]">
                            <a-input v-if="item2.groupName!=='system'" v-model="item2.labelName" :title="item2.labelName" />
                            <span v-else class="vm-label-span" :title="item2.labelName">{{ item2.labelName }}</span>
                          </template>
                          <template v-if="!item2.value&&displayFormat[showDcodeDesign]">
                            <a-input v-if="item2.groupName!=='system'" v-model="item2.displayFormat" :title="item2.displayFormat" />
                            <span v-else class="vm-label-span" :title="item2.displayFormat">{{ item2.displayFormat }}</span>
                          </template>
                        </div>
                      </template>

                    </draggable>

                  </template>

                </RecycleScroller>

              </a-col> -->

            </a-spin>
          </div>

        </a-row>
      </div>
    </draggable>
    <codemirror v-if="displayFormat2===true&&showDcodeDesign===2" v-model="htmlSourceCode" :style="{height:`calc(100% - ${headHeight-14}px)`,top:`${headHeight-18}px`}" :options="cmOptions" />
    <a-modal
      v-model="addVisible"
      :mask-closable="false"
      title=""
      :width="330"
      :dialog-style="{height:'350px'}"
      class="rt-i-modal"
      centered
      :confirm-loading="addRepReportTemplateLoading"
      @ok="insert"
      @cancel="cancelHandler"
    >
      <span slot="closeIcon" class="c-dialog-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

      <div class="c-dialog-title fw-500">填写版本号</div>
      <a-form-model
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        layout="horizontal"
      >

        <a-form-model-item label="版本号" prop="version">
          <a-input v-model="addForm.version" placeholder="版本号" class="input-type-o" style="width: 100%" />
        </a-form-model-item>
        <a-form-model-item label="生效时间" prop="effectTime">
          <a-date-picker
            v-model="addForm.effectTime"
            style="width: 100%;min-width: 100%;"
            format="YYYY-MM-DD HH:mm:ss"
            class="input-type-o"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="生效时间"
            show-time
          />
        </a-form-model-item>
        <!-- <div v-html="tmpHtml" /> -->

        <!-- <a-form-model-item label="级别" prop="level">
          <a-select
            v-model="addForm.level"
            style="minWidth: 130px"
            placeholder="请选择"
            allow-clear
          >
            <a-select-option v-for="selectItem in priorityList" :key="selectItem.id" :value="selectItem.value">
              {{ selectItem.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item> -->

      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import { mapActions, mapState } from 'vuex';
import { RecycleScroller } from 'vue-virtual-scroller';
import { toJSON, toHTML } from '@/utils/htmlParser';
import VueTree from './components/vueTreeEng';
import { codemirror } from 'vue-codemirror';
import engHtml from './components/engHtml';
import editDiv from './components/editDiv';
import 'codemirror/lib/codemirror.css';
// language
import 'codemirror/mode/xml/xml.js';
// theme css
import 'codemirror/theme/idea.css';
// require active-line.js
import 'codemirror/addon/selection/active-line.js';
// autoCloseTags
import 'codemirror/addon/edit/closetag.js';

export default {
  components: {
    draggable,
    RecycleScroller,
    codemirror,
    VueTree,
    engHtml,
    editDiv
  },
  data() {
    return {
      colonData: [
        'Hour', 'Minute', 'Second', 'Minutes'
      ],
      headHeight: 0,
      cKey: 1,
      cmOptions: {
        // codemirror options
        tabSize: 4,
        styleActiveLine: true,
        lineNumbers: true,
        line: true,
        mode: 'text/html',
        lineWrapping: true,
        theme: 'idea'
        // more codemirror options, 更多 codemirror 的高级配置...
      },
      tmpHtml: '',
      headCode: '',
      htmlSourceCode: '',
      treeData: [
        {
          name: 'test1',
          id: '1',
          children: [
            {
              name: 'test1-1',
              id: '1-1'
            }
          ]
        },
        {
          name: 'test2',
          id: '2'

        }
      ],
      addVisible: false,
      addForm: {
        version: '',
        effectTime: ''
      },
      addRules: Object.freeze({
        version: [
          { required: true, message: '请填写版本号', trigger: 'change' }
        ],
        effectTime: [
          { required: true, message: '请填写生效时间', trigger: 'change' }
        ]

        // relatedCode: [
        //   { required: true, type: 'array', message: '请选择', trigger: 'change' }
        // ]
      }),
      displayFormat1: false,
      displayFormat2: false,

      showDcodeDesign: 1,
      showSystemLabel: [],
      showNormalLabel: [],
      systemLabel: [],
      normalLabel: [],
      showNormalList: [],
      draftAc: 0,
      renderData: [],
      draftData: [],
      flag: 2,
      hisNameAc: 0,

      objData: {},
      repData: [],
      // x轴排序可能有空缺
      rowNums: [],
      // x轴排序  填满空缺
      // maxRow: [],
      // 最多列
      colMax: 0,
      rowHis: [],
      decodingDesign: {}
    };
  },
  computed: {
    ...mapState('templateManagement', [
      'repReportVersionData',
      'repReportVersionLoading',
      'addRepReportTemplateLoading',
      'updateRepReportTemplateLoading',
      'versionList'
    ]),
    tailnumbers() {
      if (Object.prototype.toString.call(this.rowHis.tailnumber) === '[object Array]') {
        return this.rowHis.tailnumber.join();
      } else {
        return this.rowHis.tailnumber;
      }
    },
    // rowHis() {
    //   return this.renderData[this.flag === 1 ? this.draftAc : 0] ?? [];
    // },
    // rowNums() {
    //   return [...new Set(this.rowHis?.templateDetails?.flatMap(item => item.row) ?? [])].sort((a, b) => a - b);
    // },

    maxRow() {
      const dataRow = this.rowHis.templateDetails ? this.rowHis.templateDetails.filter(item => item.row + item.colName !== 0) : [];
      const dataMaxRow = dataRow[dataRow.length - 1]?.row ?? 0;
      const row = [];
      for (let i = 0; i < dataMaxRow; i++) {
        row.push(i);
      }

      return row;
    }

    // colMax() {
    //   return Math.max(0, ...Object.values(this.rowTotalAll?.obj));
    // },

    // rowTotalAll() {
    //   const obj = {};
    //   const objData = {};
    //   for (const item of this.rowNums) {
    //     const rowLite = this.rowHis?.templateDetails?.filter(item2 => item2.row === item);
    //     objData[item] = rowLite;
    //     const t = rowLite.reduce((a, b) => {
    //       return a + b?.width ?? 0;
    //     }, 0);

    //     obj[item] = t;
    //   }

    //   return { obj, objData };
    // }
  },
  watch: {
    displayFormat2: {
      handler(v) {
        if (v) {
          const ttss = document.querySelector('.eng-html-box').innerHTML;
          // 移除不需要标签等
          const regHtml = ttss.replace(/<div class=".*?tmptmp.*?">(.*?)<\/div>/g, '$1').replace(/ssssable\s?/g, '').replace(/\s?class=""/g, '');
          this.htmlSourceCode = regHtml;
        } else {
          const htmljson = toJSON(this.htmlSourceCode, { skipScript: true, skipStyle: true, pureClass: false, pureComment: true });
          this.tmpHtml = htmljson;
        }
      }
    }
  },
  async mounted() {
    this.hisNameAc = 0;
    this.draftAc = 0;
    this.changeShowDcodeDesign();

    // this.getLabelParameters({ smi: 'ENG', imi: 'RTE' }).then(rep => {

    // });
  },
  methods: {
    ...mapActions('templateManagement', [
      'getTemplateManagement',
      'insertRepReportTemplate',
      'updateRepReportTemplate',
      'deleteVM',
      'getVersion'
    ]),
    // 移除标签
    removeItem(e) {
      e.item.remove();
    },
    async getTM(params = this.$route.query) {
      await this.getTemplateManagement({ ...params, templateType: this.showDcodeDesign });
      if (this.showDcodeDesign === 2) {
        this.renderTMP(this.repReportVersionData[0]);
      } else {
        this.renderTMPdecode(this.repReportVersionData[0]);
      }

      this.$nextTick(() => {
        this.headHeight = document.querySelector('.p16-a').clientHeight + 46 + 16 + 16;
      });

      // this.flag = 2;
      // this.renderData = this.repReportVersionData;

      // this.draftAc = 0;
    },
    createTree(nodes) {
      var newNodes = {};
      nodes.map(function(cur, i, arr) {
        newNodes[cur.id] = cur;
      });

      var list = [];
      for (var i = 0; i < nodes.length; i++) {
        var parent = newNodes[nodes[i].pid];
        if (parent) {
          ((parent['children']) || (parent['children'] = [])).push(nodes[i]);
        } else {
          list.push(nodes[i]);
        }
      }
      return list;
    },
    // renderTable() {
    //   this.rowHis = this.renderData[this.flag === 1 ? this.draftAc : 0] ?? [];
    //   this.rowNums = [...new Set(this.rowHis?.templateDetails?.flatMap(item => item.row) ?? [])].sort((a, b) => a - b);

    //   const rowTotal = Math.max(0, ...this.rowNums ?? []);
    //   const row = [];
    //   for (let i = 0; i < rowTotal; i++) {
    //     row.push(i);
    //   }

    //   this.maxRow = row;

    //   const colObj = {};
    //   for (const item of this.rowNums) {
    //     const rowLite = this.rowHis?.templateDetails?.filter(item2 => item2.row === item);
    //     const t = rowLite.reduce((a, b) => {
    //       return a + b?.width ?? 0;
    //     }, 0);

    //     colObj[item] = t;
    //   }

    //   this.colMax = Math.max(0, ...Object.values(colObj));
    // },
    blockFormat(v) {
      if (v.indexOf('Serial_Number') > -1) {
        return `<span class="left-number-span">${v.split('_')[2]}</span>`;
      } else {
        return '';
      }
    },
    setCurrenData() {
      const dataRow = this.rowHis.templateDetails ? this.rowHis.templateDetails.filter(item => item.row + item.colName !== 0) : [];
      const dataMaxRow = dataRow[dataRow.length - 1]?.row ?? 0;
      const fD = {};

      for (let index = 0; index <= dataMaxRow; index++) {
        const indexDora = dataRow.filter(item => item.row === index);

        fD[index] = indexDora;
      }

      this.decodingDesign = fD;
    },
    // 切换解码和显示
    async changeShowDcodeDesign() {
      this.renderData = [];
      await this.getVersion({ templateName: this.$route.query.templateName, templateType: this.showDcodeDesign });
      const versionIdIndex = this.versionList.findIndex(item => item.version === this.$route.query.version) > 0 ? this.versionList.findIndex(item => item.version === this.$route.query.version) : 0;

      this.hisNameAc = versionIdIndex;
      const versionItem = this.versionList?.[this.hisNameAc];
      if (versionItem?.version) {
        await this.getTM({ ...this.$route.query, version: versionItem.version, id: versionItem.id });
      }

      // this.renderTable();
      // this.setCurrenData();
    },

    focusSearch(e) {
      e.target.focus();
    },

    log: function(evt, rowIndex) {
      const type = Object.keys(evt)[0];
      if (type === 'moved') {
        const { newIndex, oldIndex, element } = evt.moved;
        if (newIndex < oldIndex) {
          const difN = oldIndex - newIndex;
          for (let i = 1; i <= difN; i++) {
            const index = newIndex + i;
            this.decodingDesign[element.row][index].colName += 1;
          }
        } else {
          const difN = newIndex - oldIndex;
          for (let i = 0; i < difN; i++) {
            const index = oldIndex + i;
            this.decodingDesign[element.row][index].colName -= 1;
          }
        }
        element.colName = newIndex + 1;
      } else if (type === 'added') {
        const { newIndex, element } = evt.added;
        element.row = rowIndex;
        element.colName = newIndex + 1;
        this.decodingDesign[rowIndex] ? this.decodingDesign[rowIndex] : this.$set(this.decodingDesign, rowIndex, []);
        this.decodingDesign[rowIndex][newIndex] = element;
        this.decodingDesign[rowIndex].forEach((element, index) => {
          if (index > newIndex) {
            element.colName += 1;
          }
        });
      } else if (type === 'removed') {
        const { oldIndex } = evt.removed;

        this.decodingDesign[rowIndex].forEach((element, index) => {
          if (index >= oldIndex) {
            element.colName -= 1;
          }
        });
      }
    },
    clickTab(e) {
      e.stopPropagation();
    },
    changeFlag(v) {
      this.cKey += 1;
      if (+v === 1) {
        this.draftData = localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`) ? JSON.parse(localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`)) : [];
        this.renderData = this.draftData;
        this.flag = 1;
        if (this.draftData?.length > 0) {
          this.draftClick(0);
        }
      } else {
        this.flag = 2;
        if (this.repReportVersionData?.length > 0) {
          this.hisClick(0);
        }
      }
    },

    insert() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (this.showDcodeDesign === 2) {
            let params = { id: undefined, version: this.addForm.version };
            if (!this.displayFormat2) {
              const ttss = document.querySelector('.eng-html-box').innerHTML;
              const regHtml = ttss.replace(/<div class=".*?tmptmp.*?">(.*?)<\/div>/g, '$1').replace(/ssssable\s?/g, '').replace(/\s?class=""/g, '');
              params = { ...this.repReportVersionData[0], templateDetails: [this.headCode + regHtml], ...params };
            } else {
              params = { ...this.repReportVersionData[0], templateDetails: [this.headCode + this.htmlSourceCode], ...params };
            }

            for (const key in params) {
              if (Object.hasOwnProperty.call(params, key)) {
                const element = params[key];
                if (Object.prototype.toString.call(element) === '[object Null]') {
                  params[key] = '';
                }
              }
            }

            params.tailnumber === '' ? params.tailnumber = [] : '';
            this.insertRepReportTemplate(params).then(async res => {
              if (res) {
                this.hisNameAc = 0;
                await this.getVersion({ templateName: this.$route.query.templateName, templateType: this.showDcodeDesign });
                const versionItem = this.versionList?.[this.hisNameAc];
                if (versionItem?.version) {
                  this.getTM({ ...this.$route.query, version: versionItem.version, id: versionItem.id });
                }
                this.cancelHandler();
              }
            });
          } else {
            const params = {
              ...this.rowHis,
              templateDetails: Object.values(this.decodingDesign).flat(),
              id: undefined,
              version: this.addForm.version,
              effectTime: this.addForm.effectTime
            };
            for (const key in params) {
              if (Object.hasOwnProperty.call(params, key)) {
                const element = params[key];
                if (Object.prototype.toString.call(element) === '[object Null]') {
                  params[key] = '';
                }
              }
            }
            params.tailnumber === '' ? params.tailnumber = [] : '';
            this.insertRepReportTemplate(params).then(res => {
              if (res) {
                this.hisNameAc = 0;
                this.getVersion({ templateName: this.$route.query.templateName, templateType: this.showDcodeDesign });
                this.cancelHandler();
              }
            });
          }
        } else {
          return false;
        }
      });
    },

    update() {
      if (this.showDcodeDesign === 2) {
        let params = {};
        if (!this.displayFormat2) {
          const ttss = document.querySelector('.eng-html-box').innerHTML;
          const regHtml = ttss.replace(/<div class=".*?tmptmp.*?">(.*?)<\/div>/g, '$1').replace(/ssssable\s?/g, '').replace(/\s?class=""/g, '');
          params = { ...this.repReportVersionData[0], templateDetails: [this.headCode + regHtml] };
        } else {
          params = { ...this.repReportVersionData[0], templateDetails: [this.headCode + this.htmlSourceCode] };
        }

        for (const key in params) {
          if (Object.hasOwnProperty.call(params, key)) {
            const element = params[key];
            if (Object.prototype.toString.call(element) === '[object Null]') {
              params[key] = '';
            }
          }
        }
        params.tailnumber === '' ? params.tailnumber = [] : '';
        this.updateRepReportTemplate(params);
      } else {
        const params = {
          ...this.rowHis,
          templateDetails: Object.values(this.decodingDesign).flat()
        };
        for (const key in params) {
          if (Object.hasOwnProperty.call(params, key)) {
            const element = params[key];
            if (Object.prototype.toString.call(element) === '[object Null]') {
              params[key] = '';
            }
          }
        }
        params.tailnumber === '' ? params.tailnumber = [] : '';

        this.updateRepReportTemplate(params);
      }

      // const params = {
      //   ...this.rowHis,
      //   templateDetails: Object.values(this.objData).flat()
      // };
    },
    saveDraft() {
      const params = {
        ...this.repReportVersionData[0],
        version: (this.rowHis.version.split('-')[0] ?? '0') + '-' + this.$moment.utc(new Date()).format('YYYYMMDDHHmmss')
      };
      const t = localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`) ? JSON.parse(localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`)) : [];

      t.push(params);
      this.draftData = t;
      localStorage.setItem(`draft${this.$route.query.id}${this.showDcodeDesign}`, JSON.stringify(t));
      this.rowHis = this.draftData[this.draftData.length - 1];
      this.$message.success('保存成功');

      this.cKey += 1;
    },
    draftClick(index) {
      this.cKey += 1;
      this.draftAc = +index;
      // this.renderTable();
      // this.setCurrenData();
      if (this.showDcodeDesign === 2) {
        this.renderTMP(this.draftData[this.draftAc]);
      } else {
        this.renderTMPdecode(this.draftData[this.draftAc]);
      }
    },

    async hisClick(index) {
      this.hisNameAc = +index;
      const versionItem = this.versionList?.[index];
      await this.getTM({ ...this.$route.query, version: versionItem.version, id: versionItem.id });
      // this.renderTable();
      // this.setCurrenData();
    },
    renderTMP(listData) {
      this.rowHis = listData;
      this.cKey += 1;
      const iframe = document.getElementById('rep-iframe-eng');
      // 先插入将html中的document.write执行获得完整html
      iframe.contentWindow.document.write(this.rowHis.templateDetails);
      // 根据完整html过滤script
      const htmljson = toJSON(document.getElementById('rep-iframe-eng').contentWindow.document.body.innerHTML, { skipScript: true, skipStyle: true, pureClass: false, pureComment: true });

      this.tmpHtml = htmljson;
      this.headCode = document.getElementById('rep-iframe-eng').contentWindow.document.head.innerHTML;
      // // 将iframe中dom 更新为完成html
      iframe.contentWindow.document.open();
      iframe.contentWindow.document.write(toHTML(htmljson));
      iframe.contentWindow.document.close();

      this.htmlSourceCode = document.getElementById('rep-iframe-eng').contentWindow.document.body.innerHTML;
    },
    renderTMPdecode(data) {
      this.rowHis = data;
      this.setCurrenData();
      const labelData = [...data.templateDetails.filter(item => item.row + item.colName !== 0 && item.alias.indexOf('Serial_Number') === -1 && item.alias?.trim() !== '')];
      labelData.sort((a, b) => a.alias.localeCompare(b.alias));

      // this.normalLabel = normalLabel;
      this.showNormalLabel = [...new Set(labelData)];
      // this.systemLabel = systemLabel;
      this.showSystemLabel = [];
      this.cKey += 1;
    },

    delItemHandler(item) {
      if (this.flag === 1) {
        this.draftData.splice(this.draftAc, 1);
        localStorage.setItem(`draft${this.$route.query.id}${this.showDcodeDesign}`, JSON.stringify(this.draftData));
        this.draftData = localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`) ? JSON.parse(localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`)) : [];
        this.draftClick(0);
      } else {
        this.deleteVM({ id: item.id, version: item.version }).then(async res => {
          if (res) {
            this.changeShowDcodeDesign();
          }
        });
      }
    },
    cancelHandler() {
      this.addVisible = false;
      this.addForm.version = '';
      this.$refs.addForm?.resetFields();
    },
    cloneDog(tagItem) {
      const item = {
        ...tagItem

      };
      return item;
    }
  }
};
</script>

<style lang="less" >
@import './versionManagementEng.less';
</style>
